# Base Model
import os
import click
from apiflask import APIFlask

# Import model
from app.settings import config
from app.extensions import db, mail

# import views
from app.blueprints.user.auth import auth_bp

def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')

    app = APIFlask(__name__)
    app.config.from_object(config[config_name])
    register_extensions(app)
    register_blueprints(app)

    register_commands(app)
    return app


def register_extensions(app:APIFlask):
    db.init_app(app)
    mail.init_app(app)

def register_blueprints(app:APIFlask):
    app.register_blueprint(auth_bp, url_prefix='/auth')
    # app.register_blueprint
    pass

def register_errors(app:APIFlask):
    pass

def register_commands(app:APIFlask):
    from app.models import User
    @app.cli.command()
    def initdb():
        db.create_all()
        user = User()
        user.username = "farmer"
        user.phone = "13727494636"
        user.set_password('farmer')
        user.email = "farmer-chong@qq.com"
        db.session.add(user)
        db.session.commit()
        click.echo('databases init.')
    
    @app.cli.command()
    def dropdb():
        db.drop_all()

    @app.cli.command()
    @click.option("--email", prompt=True, help="The username used to login.")
    @click.option("--username", prompt=True, help="The username used to login.")
    @click.option("--password", prompt=True, hide_input=True, help="The password used to login.")
    @click.option("--phone", prompt=True, help="The user phone.")
    def init(email, username, password, phone):
        click.echo('init system.')
        db.create_all()
        admin:User = User.query.first()
        try:
            if admin is None:
                admin = User()
            admin.username = username
            admin.phone = phone
            admin.email = email
            admin.set_password(password=password)
            admin.type = 9
            db.session.add(admin)
            db.session.commit()
        except ValueError as e:
            click.echo(e)
        

def register_logging(app:APIFlask):
    pass

